package com.ruoyi.web.controller.util;


import io.minio.*;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.TimeUnit;

@Component
public class MinioUtil {

    @Autowired
    private MinioClient minioClient;
public String upload(MultipartFile file,String fileName) throws Exception {
//确保桶存在
    createBucket();
//       上传文件
    ObjectWriteResponse response = minioClient.putObject(
            PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
    System.out.println(response);
    String url = minioClient.getPresignedObjectUrl(
            GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(bucketName)
                    .object(fileName)
                    .expiry(7, TimeUnit.DAYS)
                    .build());
    System.out.println("文件上传成功，URL: " + url);
return url;
}
    @Value("${minio.bucketName}")
    private String bucketName;
    //设置存觥栖策略为具读公开
    String policy = "{\n" +
            "\"Version\":\"2012-10-17\",\n" +
            " \"Statement\":[\n" +
            "{\n" +
            "\"Effect\":\"Allow\",\n"+
            "\"Principal\" :\"*\",\n" +
            "\"Action\":[\"s3:GetObject\"]," +
            "\"Resource\":[\"arn:aws:s3:::"+ bucketName + "/*\"]\n" +
            "}\n" +
            " ]\n" +
            " }";

    public void createBucket()throws Exception {
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
//            设置存储桶策略为只读公开
            minioClient.setBucketPolicy(
                    SetBucketPolicyArgs.builder()
                            .bucket(bucketName)
                            .config(policy)
                            .build());
        }
    }
}
